// import React from 'react';
// import ReactDOM from 'react-dom';

import React from './lib/react';
import ReactDOM from './lib/react-dom';

/**
 * 
 * forwardRef + useImperativeHandle
 *  1. forwardRef 将 ref 从父组件中转发到子组件中的 dom 元素上,子组件接受 props 和 ref 作为参数
 *  2. useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值
 */

/*
function Child(props, ref) {
  return <input ref={ref}/>
}

const ForwardChild = React.forwardRef(Child);

function Parent() {
  let [number, setNumber] = React.useState(0);
  const inputRef = React.useRef();

  const getFocus = () => {
    console.log(inputRef.current);
    inputRef.current.value = 'focus';
    inputRef.current.focus();
  }
  
  return (
    <div>
      <ForwardChild ref={inputRef}/>
      <button onClick={getFocus}>获取焦点</button>
    </div>
  )
}
*/

function Child(props, ref) {
  const inputRef = React.useRef();

  React.useImperativeHandle(ref, () => (
    {
      focus() {
        inputRef.current.focus();
      }
    }
  ));

  return (
    <input type="text" ref={inputRef} />
  )
}
const ForwardChild = React.forwardRef(Child);

function Parent() {
  let [number, setNumber] = React.useState(0);

  const inputRef = React.useRef();

  const getFocus = () => {
    console.log(inputRef.current);
    inputRef.current.value = 'focus';
    inputRef.current.focus();
  }

  return (
    <div>
      <ForwardChild ref={inputRef} />
      <button onClick={getFocus}>获得焦点</button>
      
      <p>{number}</p>
      <button onClick={() => {
        setNumber(number + 1)
      }}>+</button>
    </div>
  )
}

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);

// 注意如果要使用老的把 jsx 编译成 React.createElement(), 必须在启动项中设置 cross-env DISABLE_NEW_JSX_TRANSFORM=true
// 如： "start": "cross-env DISABLE_NEW_JSX_TRANSFORM=true react-scripts start",